<?php
class ModelSaleLgiOrder extends Model {
  public function getOrder($order_id) {
    $order_query = $this->db->query("SELECT *, (SELECT c.fullname FROM " . DB_PREFIX . "customer c WHERE c.customer_id = o.customer_id) AS customer FROM `" . DB_PREFIX . "order` o WHERE o.order_id = '" . (int)$order_id . "'");

    if ($order_query->num_rows) {
      $reward = 0;

      $order_product_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'");

      foreach ($order_product_query->rows as $product) {
        $reward += $product['reward'];
      }

      $country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$order_query->row['payment_country_id'] . "'");

      if ($country_query->num_rows) {
        $payment_iso_code_2 = $country_query->row['iso_code_2'];
        $payment_iso_code_3 = $country_query->row['iso_code_3'];
      } else {
        $payment_iso_code_2 = '';
        $payment_iso_code_3 = '';
      }

      $zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['payment_zone_id'] . "'");

      if ($zone_query->num_rows) {
        $payment_zone_code = $zone_query->row['code'];
      } else {
        $payment_zone_code = '';
      }

      $country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$order_query->row['shipping_country_id'] . "'");

      if ($country_query->num_rows) {
        $shipping_iso_code_2 = $country_query->row['iso_code_2'];
        $shipping_iso_code_3 = $country_query->row['iso_code_3'];
      } else {
        $shipping_iso_code_2 = '';
        $shipping_iso_code_3 = '';
      }

      $zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['shipping_zone_id'] . "'");

      if ($zone_query->num_rows) {
        $shipping_zone_code = $zone_query->row['code'];
      } else {
        $shipping_zone_code = '';
      }

      if ($order_query->row['affiliate_id']) {
        $affiliate_id = $order_query->row['affiliate_id'];
      } else {
        $affiliate_id = 0;
      }

      $this->load->model('marketing/affiliate');

      $affiliate_info = $this->model_marketing_affiliate->getAffiliate($affiliate_id);

      if ($affiliate_info) {
        $affiliate_fullname = $affiliate_info['fullname'];
      } else {
        $affiliate_fullname = '';
      }

      $this->load->model('localisation/language');

      $language_info = $this->model_localisation_language->getLanguage($order_query->row['language_id']);

      if ($language_info) {
        $language_code = $language_info['code'];
        $language_directory = $language_info['directory'];
      } else {
        $language_code = '';
        $language_directory = '';
      }

      return array(
        'order_id'                => $order_query->row['order_id'],
        'invoice_no'              => $order_query->row['invoice_no'],
        'invoice_prefix'          => $order_query->row['invoice_prefix'],
        'store_id'                => $order_query->row['store_id'],
        'store_name'              => $order_query->row['store_name'],
        'store_url'               => $order_query->row['store_url'],
        'customer_id'             => $order_query->row['customer_id'],
        'customer'                => $order_query->row['customer'],
        'customer_group_id'       => $order_query->row['customer_group_id'],
        'fullname'               => $order_query->row['fullname'],
        'email'                   => $order_query->row['email'],
        'telephone'               => $order_query->row['telephone'],
        'fax'                     => $order_query->row['fax'],
        'custom_field'            => json_decode($order_query->row['custom_field'], true),
        'payment_fullname'       => $order_query->row['payment_fullname'],
        'payment_company'         => $order_query->row['payment_company'],
        'payment_address'       => $order_query->row['payment_address'],
        'payment_postcode'        => $order_query->row['payment_postcode'],
        'payment_city'            => $order_query->row['payment_city'],
        'payment_city_id'            => $order_query->row['payment_city_id'],
        'payment_zone_id'         => $order_query->row['payment_zone_id'],
        'payment_zone'            => $order_query->row['payment_zone'],
        'payment_zone_code'       => $payment_zone_code,
        'payment_country_id'      => $order_query->row['payment_country_id'],
        'payment_country'         => $order_query->row['payment_country'],
        'payment_iso_code_2'      => $payment_iso_code_2,
        'payment_iso_code_3'      => $payment_iso_code_3,
        'payment_address_format'  => $order_query->row['payment_address_format'],
        'payment_custom_field'    => json_decode($order_query->row['payment_custom_field'], true),
        'payment_method'          => $order_query->row['payment_method'],
        'payment_code'            => $order_query->row['payment_code'],
        'shipping_fullname'      => $order_query->row['shipping_fullname'],
        'shipping_company'        => $order_query->row['shipping_company'],
        'shipping_address'      => $order_query->row['shipping_address'],
        'shipping_postcode'       => $order_query->row['shipping_postcode'],
        'shipping_city'           => $order_query->row['shipping_city'],
        'shipping_city_id'           => $order_query->row['shipping_city_id'],
        'shipping_zone_id'        => $order_query->row['shipping_zone_id'],
        'shipping_zone'           => $order_query->row['shipping_zone'],
        'shipping_zone_code'      => $shipping_zone_code,
        'shipping_country_id'     => $order_query->row['shipping_country_id'],
        'shipping_country'        => $order_query->row['shipping_country'],
        'shipping_iso_code_2'     => $shipping_iso_code_2,
        'shipping_iso_code_3'     => $shipping_iso_code_3,
        'shipping_address_format' => $order_query->row['shipping_address_format'],
        'shipping_custom_field'   => json_decode($order_query->row['shipping_custom_field'], true),
        'shipping_method'         => $order_query->row['shipping_method'],
        'shipping_code'           => $order_query->row['shipping_code'],
        'shipping_telephone'      => $order_query->row['shipping_telephone'],
        'comment'                 => $order_query->row['comment'],
        'total'                   => $order_query->row['total'],
        'reward'                  => $reward,
        'order_status_id'         => $order_query->row['order_status_id'],
        'affiliate_id'            => $order_query->row['affiliate_id'],
        'affiliate_fullname'     => $affiliate_fullname,
        'commission'              => $order_query->row['commission'],
        'language_id'             => $order_query->row['language_id'],
        'language_code'           => $language_code,
        'language_directory'      => $language_directory,
        'currency_id'             => $order_query->row['currency_id'],
        'currency_code'           => $order_query->row['currency_code'],
        'currency_value'          => $order_query->row['currency_value'],
        'ip'                      => $order_query->row['ip'],
        'forwarded_ip'            => $order_query->row['forwarded_ip'],
        'user_agent'              => $order_query->row['user_agent'],
        'accept_language'         => $order_query->row['accept_language'],
        'date_added'              => $order_query->row['date_added'],
        'date_modified'           => $order_query->row['date_modified'],
        'logcenter_id'            => $order_query->row['logcenter_id'],
        'is_pay'                  => $order_query->row['is_pay'],
        'sign_price'             => $order_query->row['sign_price'],
        'conform_price'             => $order_query->row['conform_price'],
        'conform_pay_status'             => $order_query->row['conform_pay_status'],
        'remarks'             => $order_query->row['remarks'],
      );
    } else {
      return;
    }
  }

  public function getOrders($data = array()) {
    $sql = "SELECT o.shipping_company,o.order_id, o.order_status_id, o.po_generated, o.fullname AS customer, (SELECT os.name FROM " . DB_PREFIX . "order_status os WHERE os.order_status_id = o.order_status_id AND os.language_id = '" . (int)$this->config->get('config_language_id') . "') AS status, o.shipping_code, o.total, o.currency_code, o.currency_value, o.date_added, o.date_modified FROM `" . DB_PREFIX . "order` o";

    if (isset($data['filter_order_status'])) {
      $implode = array();

      $order_statuses = explode(',', $data['filter_order_status']);

      foreach ($order_statuses as $order_status_id) {
        $implode[] = "o.order_status_id = '" . (int)$order_status_id . "'";
      }

      if ($implode) {
        $sql .= " WHERE (" . implode(" OR ", $implode) . ")";
      }
    } else {
      $sql .= " WHERE o.order_status_id != '16'";
    }

    if (!empty($data['filter_order_id'])) {
      $sql .= " AND o.order_id = '" . (int)$data['filter_order_id'] . "'";
    }
    
    if (isset($data['filter_order_po_generated'])) {
    	if(!empty($data['filter_order_po_generated'])){
			$sql .= " AND o.po_generated != '0' ";
    	}else{
	      	$sql .= " AND o.po_generated = '" . (int)$data['filter_order_po_generated'] . "'";
    	}
    }

    if (!empty($data['filter_customer'])) {
      $sql .= " AND o.fullname LIKE '%" . $this->db->escape($data['filter_customer']) . "%'";
    }

    if (!empty($data['filter_date_added'])) {
      $sql .= " AND DATE(o.date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
    }

    if (!empty($data['filter_date_start'])) {
      $sql .= " AND DATE(o.date_added) >= DATE('" . $this->db->escape($data['filter_date_start']) . "')";
    }

    if (!empty($data['filter_date_end'])) {
      $sql .= " AND DATE(o.date_added) <= DATE('" . $this->db->escape($data['filter_date_end']) . "')";
    }

    if (!empty($data['filter_date_modified'])) {
      $sql .= " AND DATE(o.date_modified) = DATE('" . $this->db->escape($data['filter_date_modified']) . "')";
    }

    if (!empty($data['filter_total'])) {
      $sql .= " AND o.total = '" . (float)$data['filter_total'] . "'";
    }

    //重点
    $sql .= " AND logcenter_id = '" . (int)$this->user->getLP() . "'";

    $sort_data = array(
      'o.order_id',
      'customer',
      'status',
      'o.date_added',
      'o.date_modified',
      'o.total'
    );

    if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
      $sql .= " ORDER BY " . $data['sort'];
    } else {
      $sql .= " ORDER BY o.order_id";
    }

    if (isset($data['order']) && ($data['order'] == 'DESC')) {
      $sql .= " DESC";
    } else {
      $sql .= " ASC";
    }

    if (isset($data['start']) || isset($data['limit'])) {
      if ($data['start'] < 0) {
        $data['start'] = 0;
      }

      if ($data['limit'] < 1) {
        $data['limit'] = 20;
      }

      $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
    }
    $query = $this->db->query($sql);

    return $query->rows;
  }

  public function getOrderProducts($order_id) {
    $query = $this->db->query("SELECT *,(SELECT sku FROM `".DB_PREFIX."product` p where p.product_id=order_product.product_id) as sku,(SELECT product_type FROM `".DB_PREFIX."product` p2 where p2.product_id=order_product.product_id) as product_type FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "' order BY order_ids");

    return $query->rows;
  }

  public function getchildorderproducts($order_product_id){
    $query = $this->db->query("SELECT opg.*,pd.name AS pdname,p.sku AS sku,p.model AS model FROM `".DB_PREFIX."order_product_group` opg LEFT JOIN `".DB_PREFIX."product_description` pd ON opg.product_id = pd.product_id LEFT JOIN `".DB_PREFIX."product` p ON opg.product_id = p.product_id WHERE order_product_id = '".$order_product_id."' order BY order_ids");

    return $query->rows;
  }

  public function getOrderProductsWithSku($order_id) {
    $op = M('order_product');
    $where['order_id'] = (int)$order_id;
    $opdata = $op
    ->alias('op')
    ->join('LEFT JOIN product p ON p.product_id = op.product_id')
    ->where($where)
    ->select();
    return $opdata;
  }

  public function getOrderOptions($order_id, $order_product_id) {
    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$order_product_id . "'");

    return $query->rows;
  }

  public function getOrderVouchers($order_id) {
    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_voucher WHERE order_id = '" . (int)$order_id . "'");

    return $query->rows;
  }

  public function getOrderVoucherByVoucherId($voucher_id) {
    $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order_voucher` WHERE voucher_id = '" . (int)$voucher_id . "'");

    return $query->row;
  }

  public function getOrderTotals($order_id) {
    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$order_id . "' ORDER BY sort_order");

    return $query->rows;
  }

  public function getTotalOrders($data = array()) {
    $sql = "SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order`";

    if (isset($data['filter_order_status'])) {
      $implode = array();

      $order_statuses = explode(',', $data['filter_order_status']);

      foreach ($order_statuses as $order_status_id) {
        $implode[] = "order_status_id = '" . (int)$order_status_id . "'";
      }

      if ($implode) {
        $sql .= " WHERE (" . implode(" OR ", $implode) . ")";
      }
    } else {
      $sql .= " WHERE order_status_id > '0'";
    }

    if (!empty($data['filter_order_id'])) {
      $sql .= " AND order_id = '" . (int)$data['filter_order_id'] . "'";
    }
    if (isset($data['filter_order_po_generated'])) {
    	if(!empty($data['filter_order_po_generated'])){
			$sql .= " AND o.po_generated != '0' ";
    	}else{
	     	$sql .= " AND o.po_generated = '" . (int)$data['filter_order_po_generated'] . "'";
    	}
    }
    
    if (!empty($data['filter_customer'])) {
      $sql .= " AND fullname LIKE '%" . $this->db->escape($data['filter_customer']) . "%'";
    }

    if (!empty($data['filter_date_added'])) {
      $sql .= " AND DATE(date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
    }

    if (!empty($data['filter_date_start'])) {
      $sql .= " AND DATE(date_added) > DATE('" . $this->db->escape($data['filter_date_start']) . "')";
    }

    if (!empty($data['filter_date_end'])) {
      $sql .= " AND DATE(date_added) < DATE('" . $this->db->escape($data['filter_date_end']) . "')";
    }

    if (!empty($data['filter_date_modified'])) {
      $sql .= " AND DATE(date_modified) = DATE('" . $this->db->escape($data['filter_date_modified']) . "')";
    }

    if (!empty($data['filter_total'])) {
      $sql .= " AND total = '" . (float)$data['filter_total'] . "'";
    }

    $sql .= " AND logcenter_id = '" . (int)$this->user->getLP() . "'";

    $query = $this->db->query($sql);

    return $query->row['total'];
  }

  public function getTotalOrdersByStoreId($store_id) {
    $query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE store_id = '" . (int)$store_id . "'");

    return $query->row['total'];
  }

  public function getTotalOrdersByOrderStatusId($order_status_id) {
    $query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE order_status_id = '" . (int)$order_status_id . "' AND order_status_id > '0'");

    return $query->row['total'];
  }

  public function getTotalOrdersByProcessingStatus() {
    $implode = array();

    $order_statuses = $this->config->get('config_processing_status');

    foreach ($order_statuses as $order_status_id) {
      $implode[] = "order_status_id = '" . (int)$order_status_id . "'";
    }

    if ($implode) {
      $query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE " . implode(" OR ", $implode));

      return $query->row['total'];
    } else {
      return 0;
    }
  }

  public function getTotalOrdersByCompleteStatus() {
    $implode = array();

    $order_statuses = $this->config->get('config_complete_status');

    foreach ($order_statuses as $order_status_id) {
      $implode[] = "order_status_id = '" . (int)$order_status_id . "'";
    }

    if ($implode) {
      $query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE " . implode(" OR ", $implode) . "");

      return $query->row['total'];
    } else {
      return 0;
    }
  }

  public function getTotalOrdersByLanguageId($language_id) {
    $query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE language_id = '" . (int)$language_id . "' AND order_status_id > '0'");

    return $query->row['total'];
  }

  public function getTotalOrdersByCurrencyId($currency_id) {
    $query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE currency_id = '" . (int)$currency_id . "' AND order_status_id > '0'");

    return $query->row['total'];
  }

  public function createInvoiceNo($order_id) {
    $order_info = $this->getOrder($order_id);

    if ($order_info && !$order_info['invoice_no']) {
      $query = $this->db->query("SELECT MAX(invoice_no) AS invoice_no FROM `" . DB_PREFIX . "order` WHERE invoice_prefix = '" . $this->db->escape($order_info['invoice_prefix']) . "'");

      if ($query->row['invoice_no']) {
        $invoice_no = $query->row['invoice_no'] + 1;
      } else {
        $invoice_no = 1;
      }

      $this->db->query("UPDATE `" . DB_PREFIX . "order` SET invoice_no = '" . (int)$invoice_no . "', invoice_prefix = '" . $this->db->escape($order_info['invoice_prefix']) . "' WHERE order_id = '" . (int)$order_id . "'");

      return $order_info['invoice_prefix'] . $invoice_no;
    }
  }

  public function getOrderHistories($order_id, $start = 0, $limit = 10) {
    if ($start < 0) {
      $start = 0;
    }

    if ($limit < 1) {
      $limit = 10;
    }

    $query = $this->db->query("SELECT oh.date_added, os.name AS status, oh.comment, oh.notify, oh.vendor_id FROM " . DB_PREFIX . "order_history oh LEFT JOIN " . DB_PREFIX . "order_status os ON oh.order_status_id = os.order_status_id WHERE oh.order_id = '" . (int)$order_id . "' AND os.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY oh.date_added ASC LIMIT " . (int)$start . "," . (int)$limit);

    return $query->rows;
  }

  public function getTotalOrderHistories($order_id) {
    $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "order_history WHERE order_id = '" . (int)$order_id . "'");

    return $query->row['total'];
  }

  public function getTotalOrderHistoriesByOrderStatusId($order_status_id) {
    $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "order_history WHERE order_status_id = '" . (int)$order_status_id . "'");

    return $query->row['total'];
  }

  public function getEmailsByProductsOrdered($products, $start, $end) {
    $implode = array();

    foreach ($products as $product_id) {
      $implode[] = "op.product_id = '" . (int)$product_id . "'";
    }

    $query = $this->db->query("SELECT DISTINCT email FROM `" . DB_PREFIX . "order` o LEFT JOIN " . DB_PREFIX . "order_product op ON (o.order_id = op.order_id) WHERE (" . implode(" OR ", $implode) . ") AND o.order_status_id <> '0' LIMIT " . (int)$start . "," . (int)$end);

    return $query->rows;
  }

  public function getAllVendorOrderStatus($order_id) {
    $getOrderStatusID = $this->db->query("SELECT order_status_id FROM  `" . DB_PREFIX . "order` WHERE order_id = '" . (int)$order_id . "'");
    $count1 = $this->db->query("SELECT COUNT(*) as total FROM  `" . DB_PREFIX . "order_status_vendor_update` WHERE order_id = '" . (int)$order_id . "'");
    $count2 = $this->db->query("SELECT COUNT(*) as total FROM  `" . DB_PREFIX . "order_status_vendor_update` WHERE order_id = '" . (int)$order_id . "' AND order_status_id = '" . (int)$getOrderStatusID->row['order_status_id'] . "'");

    if ($count1->row['total'] != $count2->row['total']) {
      $query = $this->db->query("SELECT DISTINCT(`vendor_id`), order_status_id FROM  `" . DB_PREFIX . "order_status_vendor_update` WHERE order_id = '" . (int)$order_id . "'");
      $status_text = '';
          
      if ($query->rows) {
        foreach ($query->rows as $result) {           
          $name = $this->db->query("SELECT vendor_name FROM  `" . DB_PREFIX . "vendors` WHERE vendor_id = '" . (int)$result['vendor_id'] . "'");
          $status = $this->db->query("SELECT name FROM  `" . DB_PREFIX . "order_status` WHERE order_status_id = '" . (int)$result['order_status_id'] . "'");
                
          if ($name->row) {
            $vname = $name->row['vendor_name'];
          } else {
            $vname = '';
          }
              
          if ($vname) {
            if (empty($status_text)) {
              $status_text = '<small><b>' . $vname . '</b> - ' . $status->row['name'] . '</small>';
            } else {
              $status_text .= '<br /><small><b>' . $vname . '</b> - ' . $status->row['name'] . '</small>';
            }             
          }
        }
        return $status_text;
      } else {
        return false;
      }
    } else {
      $current_status = $this->db->query("SELECT name FROM  `" . DB_PREFIX . "order_status` WHERE order_status_id = '" . (int)$getOrderStatusID->row['order_status_id'] . "'");
      return $current_status->row['name'];
    }
  }

  public function getTotalEmailsByProductsOrdered($products) {
    $implode = array();

    foreach ($products as $product_id) {
      $implode[] = "op.product_id = '" . (int)$product_id . "'";
    }

    $query = $this->db->query("SELECT DISTINCT email FROM `" . DB_PREFIX . "order` o LEFT JOIN " . DB_PREFIX . "order_product op ON (o.order_id = op.order_id) WHERE (" . implode(" OR ", $implode) . ") AND o.order_status_id <> '0'");

    return $query->row['total'];
  }

  private function getOrdersByCustomerId($customer_id){
    if(!($customer_id)){
      $customer_id = 0;
    }
    $order = M('order');
    $where['customer_id'] =$customer_id;
    $query = $order
    ->where($where)
    ->field('SUM(total) as total,count(*) as count')
    ->where("date_format(date_added,'%Y-%m') = date_format(now(),'%Y-%m')")
    ->where("order_status_id in (" .implode(',', array_merge($this->config->get('config_complete_status'), $this->config->get('config_processing_status'))). ")")
    ->select();
    if($query['0']['count']){
      $count = $query['0']['count'];
    }else{
      $count = 0;
    }
    if($query['0']['total']){
      $total = $query['0']['total'];
    }else{
      $total = 0.0000;
    }
    $data = array(
      'count' => $count,
      'total' => $total,
      );
    return $data;
  }

  public function getOrderProductsDetial($order_id){
    $op = M('order_product');
    if(!($order_id)){
      $order_id = 0;
    }
    $where['op.order_id'] = $order_id;
    $query = $op
    ->alias('op')
    ->join("LEFT JOIN `product` p ON op.product_id = p.product_id ")
    ->where($where)
    ->field('op.name,op.price,op.quantity,p.sku,op.total,p.product_type,op.order_product_id,op.order_ids')
    ->order('order_ids')
    ->select();
    return $query;
  }

  public function getSc($order_id){
    $order = M('order');
    if(!($order_id)){
      $where['order_id'] = 0 ;
    }
  
    $query = $this->getOrder($order_id);
    $user_id = $this ->user->getLP();
    
    if($user_id == $query['logcenter_id']){
      $this->load->model('customer/customer');
      $reward = $this->model_customer_customer->getMreward($query['customer_id']);
      $money = $this->getOrdersByCustomerId($query['customer_id']); 
      $customer_info = $this->model_customer_customer->getCustomer($query['customer_id']); 
      $data = array();    
      $data = array(
        'order_id'      => $query['order_id'], 
        'date_added'    => $query['date_added'],
        'fullname'      => $query['fullname'],
        'customer_id'   => $query['customer_id'],
        'shipping_fullname' => $query['shipping_fullname'],
        'telephone'     => $query['telephone'],
        'payment_method' => $query['payment_method'],
        'is_pay' => $query['is_pay'],
        'Mreward'         => $reward['Mreward'],
        'Areward'     => $reward['Areward'],
        'Mtotal_order'    => $money['count'],
        'Mtotal_money'    => $money['total'],
        'shipping_address'    => $query['shipping_country'].$query['shipping_zone'].$query['shipping_city'].$query['shipping_address'],
        'total' => $query['total'],
        'company_name' => $customer_info['company_name'],
        'payment_method' => $query['payment_method'],
        'is_pay' => $query['is_pay']
        );
      $total_item_number = 0;
      $products = $this->getOrderProductsDetial($order_id);
      if($products){
        foreach ($products as $result) {
          if($result['product_type'] != 2){
            $data['products'][] = array(
              'product_name'  => $result['name'],
              'sku'       => $result['sku'],
              'quantity'    => $result['quantity'],
              'price'     => $result['price'],
              'total'     => $result['total'], 
	          'order_ids'     => $result['order_ids'], 
              );  
            $total_item_number+=$result['quantity'];
          }else{
            $childproducts = $this->getchildorderproducts($result['order_product_id']);
            foreach($childproducts as $val){
              $data['products'][] = array(
                'product_name'  => $val['pdname'].'('.$result['name'].')',
                    'sku'       => $val['sku'],
                    'quantity'    => $val['quantity'],
                    'price'     => $val['price'],
                    'total'     => $val['total'], 
		          'order_ids'     => $result['order_ids'].'-'.$val['order_ids'], 
              );
              $total_item_number+=$result['quantity'];
            }
          }
        } 
      }
      $data['total_item_number'] = $total_item_number;
    }
    
    return $data;
  }

  public function getOrderProductByOrderProductId($order_product_id){
    $op = M('order_product');
    $where['order_product_id'] = $order_product_id;
    $query = $op
    ->where($where)
    ->find();
    if($query){
      $result = true;
    }else{
      $result = false;
    }
    return $result;
  }

  public function saveOrderProductStatus($status_id,$order_product_id){
    $op = M('order_product');
    $data['ship_status'] = $status_id;
    $data['shipped_time'] = date('Y-m-d h:i:s');
 
    $where['order_product_id'] = $order_product_id;
    if($status_id == 1 || $status_id == 0){
      $query = $op
      ->where($where)
      ->data($data)
      ->save();
    }
    return $query;
  }

  public function checkLogcenterByOrderProductId($order_product_id){
    $logcenter_id = $this->user->getLP();
    $logcenter_id_p = $this->getLogcenterIdByOrderProductId($order_product_id);
    if($logcenter_id == $logcenter_id_p){
      $result = true;
    }else{
      $result = false;
    }
    return $result;
  }

  private function getLogcenterIdByOrderProductId($order_product_id){

    $op = M('order_product');
    if(!($order_product_id)){
      $order_product_id = 0;
    }
    $query = $op
    ->alias('op')
    ->join('LEFT JOIN `order` o ON o.order_id = op.order_id')
    ->field('o.logcenter_id')
    ->where('op.order_product_id = '.$order_product_id)
    ->find();
    return $query['logcenter_id'];

  }
  public function checkLogcenterByOrderId($order_id){
    $logcenter_id = $this->user->getLP();
    $logcenter_id_p = $this->getLogcenterIdByOrderId($order_id);
    if($logcenter_id == $logcenter_id_p){
      $result = true;
    }else{
      $result = false;
    }
    return $result;
  }

  private function getLogcenterIdByOrderId($order_id){

    $o = M('order');
    if(!($order_id)){
      $order_id = 0;
    }
    $where['order_id'] = $order_id;
    $query = $o
    ->where($where)
    ->field('logcenter_id')
    ->find();  
    return $query['logcenter_id'];

  }

  public function saveAllOrderProductStatus($status_id,$order_id){
    $op = M('order_product');
    $data['ship_status'] = $status_id;
    $data['shipped_time'] = date('Y-m-d h:i:s');
    $where['order_id'] = $order_id;
    if($status_id == 1 || $status_id == 0){
      $query = $op
      ->where($where)
      ->data($data)
      ->save();
    }
    return $query;
  }

  public function getOrderIdByOrderProductId($order_product_id) {
    $op = M('order_product')->where(array("order_product_id"=>$order_product_id))->find();
    if($op) {
      return $op['order_id'];
    } else {
      return 0;
    }
  }

  public function checkSippingStatus($order_id) {
    //0:待发货，1:部分发货，2:全部发货
    $ops = M('order_product')->where(array("order_id"=>$order_id))->select();
    $total_item_number = count($ops);
    $shipped_item_number = 0;
    foreach ($ops as $op) {
      if($op['ship_status'] == 1) {
        $shipped_item_number++;
      }
    }
    if ($shipped_item_number == 0) {
      return 0;
    }
    if ($shipped_item_number == $total_item_number) {
      return 2;
    }
    return 1;
  }

  public function getOrderStatusIdByShippingStatus($shipping_status) {
    $shipping_status_to_order_status_name_map = array(0=>'待发货', 1=>'部分发货', 2=>'全部发货');
    $order_status_name = $shipping_status_to_order_status_name_map[$shipping_status];
    $os = M('order_status');
    $query = $os->where(array('name'=>$order_status_name))->find();
    if($query) {
      return $query['order_status_id'];
    } else {
      return 0;
    }
  }

  public function getLogcenters($filter_name=''){
    $where['logcenter_name'] = array('like','%'.$filter_name.'%');
    $where['user_id'] = array('neq',$this->user->getId());
    $logcenters =  M('logcenters')
    ->limit(5)
    ->where($where)
    ->select();
    return $logcenters;
  }

  public function getAllLogcenters(){

    $logcenters =  M('logcenters')
    ->field('logcenter_id,logcenter_name')
    ->select();
    return $logcenters;
  }

  public function getToProveOrderStatus() {
    $shipped_status_name = '待审核';
    $query = $this->db->query("SELECT DISTINCT `order_status_id` FROM `" . DB_PREFIX . "order_status` WHERE 
      `language_id` = '" . (int)$this->config->get('config_language_id') . "' AND `name` = '" . $shipped_status_name . "'" );
    $rslt = $query->row; 
    return $rslt['order_status_id'];
  }

  public function setOrderToProve($order_id) {
    $order_status_id = $this->getToProveOrderStatus();
    $this->db->query("UPDATE `" . DB_PREFIX . "order` SET order_status_id = '" . (int)$order_status_id . "' WHERE order_id = '" . (int)$order_id . "'");
  }

}